package org.springblade.modules.restaurant.job;

import cn.hutool.core.date.DateUtil;
import com.aizuda.snailjob.client.job.core.annotation.JobExecutor;
import com.aizuda.snailjob.client.job.core.dto.JobArgs;
import com.aizuda.snailjob.client.model.ExecuteResult;
import com.aizuda.snailjob.common.log.SnailJobLog;
import lombok.AllArgsConstructor;
import org.springblade.modules.restaurant.entity.CommodityRecord;
import org.springblade.modules.restaurant.entity.CommodityRecordRelation;
import org.springblade.modules.restaurant.enums.CommodityRecordStatusEnums;
import org.springblade.modules.restaurant.service.ICommodityRecordRelationService;
import org.springblade.modules.restaurant.service.ICommodityRecordService;
import org.springframework.stereotype.Component;

/**
 * 更新未审核的采购记录状态为已过期
 *
 * @author harry
 * @公众号 Harry技术
 */
@Component
@AllArgsConstructor
@JobExecutor(name = "commodityRecordStatusUpdateJobExecutor")
public class CommodityRecordStatusUpdateJobExecutor {
	private final ICommodityRecordService commodityRecordService;
	private final ICommodityRecordRelationService commodityRecordRelationService;

	public ExecuteResult jobExecute(JobArgs jobArgs) {
		SnailJobLog.REMOTE.info("更新未审核的采购记录状态为已过期,jobArgs:{}", jobArgs);

		// 更新采购记录状态
		commodityRecordService.lambdaUpdate()
			.eq(CommodityRecord::getStatus, CommodityRecordStatusEnums.WAIT_AUDIT.getStatus())
			.lt(CommodityRecord::getCreateTime, DateUtil.endOfDay(DateUtil.yesterday()))

			.set(CommodityRecord::getStatus, CommodityRecordStatusEnums.EXPIRED.getStatus()).update();

		// 更新关联表状态
		commodityRecordRelationService.lambdaUpdate()
			.eq(CommodityRecordRelation::getStatus, CommodityRecordStatusEnums.WAIT_AUDIT.getStatus())
			.lt(CommodityRecordRelation::getCreateTime, DateUtil.endOfDay(DateUtil.yesterday()))

			.set(CommodityRecordRelation::getStatus, CommodityRecordStatusEnums.EXPIRED.getStatus()).update();

		return ExecuteResult.success();
	}

//	@PostConstruct
	public void init() {
		// 更新采购记录状态
		commodityRecordService.lambdaUpdate()
			.eq(CommodityRecord::getStatus, CommodityRecordStatusEnums.WAIT_AUDIT.getStatus())
			.lt(CommodityRecord::getCreateTime, DateUtil.endOfDay(DateUtil.yesterday()))

			.set(CommodityRecord::getStatus, CommodityRecordStatusEnums.EXPIRED.getStatus()).update();

		// 更新关联表状态
		commodityRecordRelationService.lambdaUpdate()
			.eq(CommodityRecordRelation::getStatus, CommodityRecordStatusEnums.WAIT_AUDIT.getStatus())
			.lt(CommodityRecordRelation::getCreateTime, DateUtil.endOfDay(DateUtil.yesterday()))

			.set(CommodityRecordRelation::getStatus, CommodityRecordStatusEnums.EXPIRED.getStatus()).update();

	}
}
